import { checkLogin } from "../../utils/util"

// pages/mine/index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

    /**
     * 页面的初始数据
     */
    data: {
      avatarUrl: defaultAvatarUrl
    },

    tapLogin: function() {
      wx.navigateTo({
        url: '../login/index',
      })
    },
    tapEnroll: function() {
      wx.navigateTo({
        url: '../enroll/enroll',
      })
    },

    tapSubUser: function() {
        wx.navigateTo({
          url: './subUser/index',
        })
    },

    tapUpdatePwd: function() {
        wx.navigateTo({
          url: './pwd/pwd',
        })
    },

    tapLogout: function() {
        const {userId} = wx.getStorageSync('szm_token') || {}
        wx.$http.put({url: '/szm/logout/' + userId}).then(()=>{
            wx.removeStorageSync('szm_token')
            wx.showToast({
              title: '退出',
            })
            setTimeout(()=> wx.switchTab({
                url: '/pages/index/index',
              }), 2000)
        })
        
    },

    tapUnbindWx: function() {
        const {openid} = wx.getStorageSync('wechatInfo');
        wx.$http.put({url: `/wechat/unbind/`, data: {openid}}).then(()=>{
            wx.showToast({
              title: '解除自动登录',
            })
        })
        
    },

    tapRecharge: function () {
      wx.navigateToMiniProgram({
        appId: 'wxfef094f195354bdf',
        path: 'pages/index/index',
      // extraData: this.data.options,
      // envVersion: Config().envVersion,
      success(res) {
        console.log('====navigateToMiniProgram success====');
      }
    })
    },

    getUserInfo() {
      const {userId} = wx.getStorageSync('szm_token');
      wx.$http.get({url: `/szm/user/${userId}`}).then(res => {
        const {id, loginName, name, avatar} = res.data;
        const userInfo = {
          avatar,
          loginName,
          name,
          id
        }
        this.setData({userInfo});
      });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      
      if (checkLogin("no")) {
        this.setData({isLogout: false})
        this.getUserInfo()
      } else {
        this.setData({isLogout: true})
      }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async onChooseAvatar(e) {
      const { avatarUrl } = e.detail 
      const {userInfo} = this.data;
     
      const key = `szm/avatar/${avatarUrl.match(/[^/]+$/)[0]}`
      if(userInfo.avatar) {
        await wx.$http.post({otherBaseUrl: "https://promp.ugogosmart.com/boray-wechat", url: "/upload/delete", data: {key: userInfo.avatar.match(/saas\/avatar[^?]+/)[0]}}).then();
      }
      this.upload(avatarUrl, key);
    },
  
    async upload(avatarUrl, key) {
      console.log('upload ==', {avatarUrl, key})
      
      // const res = await wx.$http.get({url: `/sys/oss/getToken?token=${wx.getStorageSync('saas_token').token}`});
      // const {token, domain} = res.data;
  
      const res = await wx.$http.post({otherBaseUrl: "https://promp.ugogosmart.com/boray-wechat", url: "/upload/getToken", data: {key}});
      const {uploadToken} = res.data;
      const domain = `https://proimg.bosdon.com.cn/`
      wx.uploadFile({
        url: `https://up-z2.qiniup.com`, //仅为示例，非真实的接口地址
        filePath: avatarUrl,
        name: 'file',
        formData: {
          'token': uploadToken,
          'key': key
        },
        success: (res)=>{
          console.log(res)
          const avatar = `${domain + key}?t=${Date.now()}`;
          const {userInfo} = this.data;
          userInfo.avatar = avatar;
          this.setData({userInfo})
          wx.$http.put({url: `/szm/user/update`, data: {id: userInfo.id, avatar}});
        },
        fail(err){
          console.error(err)
        }
      })
    },

    test() {
      wx.$http.post({url: "/third/deviceInfo", data: {account: "sub01", deviceId: "test34567800", state: 1, lockPwd: "ddddddddd", lampsPwd: "fffffffffff"}})
    }
})